<template>
    <div class="reward-management">
        <el-card>
            <!-- 搜索表单 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="用户ID:">
                    <el-input v-model="searchForm.user_id" placeholder="请输入用户ID" style="width: 150px;" clearable />
                </el-form-item>
                <el-form-item label="活动名称:">
                    <el-input v-model="searchForm.activity_name" placeholder="请输入活动名称" style="width: 180px;"
                        clearable />
                </el-form-item>
                <el-form-item label="审核状态:">
                    <el-select v-model="searchForm.status" placeholder="请选择审核状态" style="width: 120px;" clearable>
                        <el-option label="审核中" :value="1" />
                        <el-option label="通过" :value="2" />
                        <el-option label="拒绝" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getList" :loading="loading">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table :data="tableData" border v-loading="loading" style="width: 100%;margin-top: 20px;">
                <el-table-column prop="username" align="center" label="用户名" width="120" />
                <el-table-column prop="activity_name" align="center" label="活动名称" width="180" />
                <el-table-column prop="source" align="center" label="来源" width="60" />
                <el-table-column prop="link" label="提交链接" align="center" min-width="120">
                    <template slot-scope="scope">
                        <el-link :href="fixUrl(scope.row.link)" target="_blank" type="primary">
                            {{ scope.row.link }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column label="主页截图" align="center" prop="file" width="200">
                    <template slot-scope="scope">
                        <div v-if="scope.row.file">
                            <img :src="scope.row.file" alt="Image"
                                style="max-width: 100px; max-height: 100px; cursor: pointer;"
                                @click="openDialog(scope.row.file)" />
                        </div>
                        <div v-else>
                            --
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="apply_time" align="center" label="申请时间" width="155">
                    <template slot-scope="scope">
                        {{ formatTime(scope.row.apply_time) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" align="center" label="状态" width="100">
                    <template slot-scope="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ getStatusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="audit_time" align="center" label="审核时间" width="155">
                    <template slot-scope="scope">
                        {{ scope.row.audit_time ? formatTime(scope.row.audit_time) : '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" v-if="scope.row.status != 1" type="primary"
                            @click="viewDetail(scope.row)">
                            详情
                        </el-button>
                        <el-button size="mini" v-if="scope.row.status === 1" type="warning"
                            :loading="auditBtnLoading[scope.row.id]" :disabled="!!auditBtnLoading[scope.row.id]"
                            @click="openAuditDialog(scope.row)">
                            审核
                        </el-button>

                        <!-- <el-button v-else-if="scope.row.status === 2" size="mini" type="success" disabled>
                            已通过
                        </el-button>
                        <el-button v-else-if="scope.row.status === 3" size="mini" type="danger" disabled>
                            已拒绝
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination @current-change="handlePageChange" @size-change="handleSizeChange" :current-page="page"
                :page-size="size" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
                :total="total" style="margin:20px 0 0;text-align:right;" />
        </el-card>

        <!-- 审核弹框 -->
        <el-dialog title="申请审核" :visible.sync="auditDialog.visible" width="600px" @close="resetAuditForm">
            <!-- 审核奖励配置正在加载时的 loading 提示 -->
            <div v-if="auditDialogLoading" style="text-align:center;padding:40px 0;">
                <el-spinner type="fading-circle" /> 奖励项加载中...
            </div>

            <!-- 弹窗核心内容（加载成功才显示） -->
            <div v-else>
                <!-- 审核基本信息 -->
                <div v-if="auditDialog.currentRow" class="audit-info">
                    <el-descriptions :column="1" border size="small" style="margin-bottom: 20px;">
                        <el-descriptions-item label="用户名">{{ auditDialog.currentRow.username }}</el-descriptions-item>
                        <el-descriptions-item
                            label="活动名称">{{ auditDialog.currentRow.activity_name }}</el-descriptions-item>
                        <el-descriptions-item label="提交链接">
                            <el-link :href="fixUrl(auditDialog.currentRow.link)" target="_blank" type="primary">
                                {{ auditDialog.currentRow.link }}
                            </el-link>
                        </el-descriptions-item>
                        <el-descriptions-item
                            label="申请次数">{{ auditDialog.currentRow.apply_count }}</el-descriptions-item>
                        <el-descriptions-item label="已领奖励">
                            <div
                                v-if="auditDialog.currentRow.granted_rewards_list && auditDialog.currentRow.granted_rewards_list.length > 0">
                                <el-tag v-for="(reward, index) in auditDialog.currentRow.granted_rewards_list"
                                    :key="index" type="success" style="margin-right: 10px; margin-bottom: 5px;">
                                    {{
                                        typeof reward === 'string'
                                            ? reward
                                            : (reward.reward_name + (reward.momo_amount ? ('（+' + reward.momo_amount + '币）') : ''))
                                    }}
                                </el-tag>
                            </div>
                            <span v-else>无</span>
                        </el-descriptions-item>
                        <el-descriptions-item label="主页截图">
                            <div v-if="auditDialog.currentRow.file">
                                <img :src="auditDialog.currentRow.file" alt="Image"
                                    style="max-width: 100px; max-height: 100px; cursor: pointer;"
                                    @click="openDialog(auditDialog.currentRow.file)" />
                            </div>
                            <div v-else>
                                --
                            </div>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>

                <!-- 审核表单区域 -->
                <el-form :model="auditForm" label-width="80px" :rules="auditRules" ref="auditFormRef">
                    <el-form-item label="审核结果" prop="status">
                        <el-radio-group v-model="auditForm.status">
                            <el-radio :label="2">通过</el-radio>
                            <el-radio :label="3">拒绝</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="auditForm.status === 2 ? '备注说明' : '备注说明'"
                        :prop="auditForm.status === 3 ? 'reason' : ''">
                        <el-input v-model="auditForm.reason" type="textarea" rows="3"
                            :placeholder="auditForm.status === 2 ? '可填写备注说明（选填）' : '请输入拒绝原因（必填）'" maxlength="500"
                            show-word-limit />
                    </el-form-item>
                    <el-form-item v-if="auditForm.status === 2" label="奖励配置" prop="rewards">
                        <el-select v-model="auditForm.rewards" multiple placeholder="请选择奖励内容" style="width: 100%;">
                            <el-option v-for="(item, idx) in rewardOptions" :key="idx"
                                :label="item.reward_name + (item.momo_amount ? '（+' + item.momo_amount + 'momo币）' : '')"
                                :value="JSON.stringify(item)" />
                        </el-select>
                        <div class="form-tip">选择该申请可获得的奖励内容</div>
                    </el-form-item>
                </el-form>

                <!-- 审核操作按钮 -->
                <div slot="footer" class="dialog-footer">
                    <el-button @click="auditDialog.visible = false">取消</el-button>
                    <el-button :type="auditForm.status === 2 ? 'success' : 'danger'" @click="submitAudit"
                        :loading="auditLoading">
                        {{ auditForm.status === 2 ? '确认通过' : '确认拒绝' }}
                    </el-button>
                </div>
            </div>
        </el-dialog>


        <!-- 详情弹窗 -->
        <el-dialog title="申请详情" :visible.sync="detailDialogVisible" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="用户ID">{{ detailData.user_id }}</el-descriptions-item>
                <el-descriptions-item label="活动名称">{{ detailData.activity_name }}</el-descriptions-item>
                <el-descriptions-item label="来源">{{ detailData.source }}</el-descriptions-item>
                <el-descriptions-item label="提交链接" :span="2">
                    <el-link :href="fixUrl(detailData.link)" target="_blank"
                        type="primary">{{ detailData.link }}</el-link>
                </el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ formatTime(detailData.apply_time) }}</el-descriptions-item>
                <el-descriptions-item
                    label="审核时间">{{ detailData.audit_time ? formatTime(detailData.audit_time) : '未审核' }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusType(detailData.status)">
                        {{ getStatusText(detailData.status) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="备注说明" :span="2">{{ detailData.reason || '无' }}</el-descriptions-item>
                <el-descriptions-item label="奖励内容" :span="2">
                    <div v-if="detailData.rewards && detailData.rewards.length > 0">
                        <el-tag v-for="(reward, index) in detailData.rewards" :key="index" type="success"
                            style="margin-right: 10px; margin-bottom: 5px;">
                            {{ typeof reward === 'string' ? reward : (reward.reward_name + (reward.momo_amount ? '（+' + reward.momo_amount + '币）' : '')) }}
                        </el-tag>
                    </div>
                    <span v-else>无</span>
                </el-descriptions-item>
                <el-descriptions-item label="主页截图" :span="2">
                    <div v-if="detailData.file">
                        <img :src="detailData.file" alt="Image"
                            style="max-width: 100px; max-height: 100px; cursor: pointer;"
                            @click="openDialog(detailData.file)" />
                    </div>
                    <div v-else>
                        --
                    </div>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible" @close="dialogVisible = false">
            <img :src="currentImageUrl" alt="Large Image" style="width: 100%;" />
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

const API_BASE = "https://xiaoshuchengzhang.com/node/Transir"
// const API_BASE = "http://127.0.0.1:5000/node/Transir"

export default {
    data() {
        return {
            loading: false,
            auditLoading: false,
            auditBtnLoading: {},
            tableData: [],
            page: 1,
            size: 10,
            total: 0,
            searchForm: {
                user_id: '',
                activity_name: '',
                status: ''
            },
            auditDialog: {
                visible: false,
                currentRow: null
            },
            auditForm: {
                status: 2, // 默认选择通过
                reason: '',
                rewards: []
            },
            auditRules: {
                status: [
                    { required: true, message: '请选择审核结果', trigger: 'change' }
                ],
                reason: [
                    { required: true, message: '请输入拒绝原因', trigger: 'blur' }
                ],
                rewards: [
                    {
                        validator: function (rule, value, callback) {
                            if (this.auditForm.status === 2 && (!value || value.length === 0)) {
                                callback(new Error('请选择奖励内容'));
                            } else {
                                callback();
                            }
                        }.bind(this),
                        trigger: 'change'
                    }
                ]
            },
            rewardOptions: [], // 审核通过奖励可选项
            detailDialogVisible: false,
            detailData: {},
            auditBtnLoading: {},   // 每个审核按钮的loading
            auditDialogLoading: false,   // 弹框内 loading（如奖励项接口未返回）
            currentImageUrl: '',
            dialogVisible: false,
         

        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        fixUrl(url) {
            if (!url) return '#'
            // 如果已经带有 http 或 https 直接返回
            if (/^https?:\/\//i.test(url)) {
                return url
            }
            // 否则自动加上 http://
            return 'http://' + url
        },
        openDialog(url) {
            this.currentImageUrl = url;
            this.dialogVisible = true;
        },
        // 获取奖励申请列表
        async getList() {
            this.loading = true
            try {
                const params = {
                    page: this.page,
                    size: this.size,
                    ...this.searchForm
                }
                let { data: res } = await axios.post(API_BASE + '/reward/apply/list', params)
                this.loading = false
                if (res.code === 0) {
                    this.tableData = res.data.list || []
                    this.total = res.data.total || 0
                    // 兼容后端rewards存json字符串的情况
                    this.tableData.forEach(item => {
                        if (item.rewards && typeof item.rewards === 'string') {
                            try { item.rewards = JSON.parse(item.rewards) } catch { item.rewards = [] }
                        }


                    })
                    console.log(this.tableData)
                } else {
                    this.$message.error(res.msg || '获取失败')
                }
            } catch (e) {
                this.loading = false
                this.$message.error(e.message || '获取失败')
            }
        },
        // 查询与重置
        resetSearch() {
            this.searchForm = {
                user_id: '',
                activity_name: '',
                status: ''
            }
            this.page = 1
            this.getList()
        },
        // 分页
        handlePageChange(val) {
            this.page = val
            this.getList()
        },
        handleSizeChange(val) {
            this.size = val
            this.page = 1
            this.getList()
        },
        // 打开审核弹窗
        async openAuditDialog(row) {
            // 防连点，点了就loading
            this.$set(this.auditBtnLoading, row.id, true);

            this.auditDialogLoading = true;
            this.auditDialog.visible = false;
            this.auditDialog.currentRow = row;
            this.resetAuditForm();
            this.rewardOptions = [];

            try {
                let { data: res } = await axios.post(API_BASE + '/activity/reward_options', { activity_id: row.activity_id, lang: row.source });
                if (res.code === 0 && Array.isArray(res.data)) {
                    this.rewardOptions = res.data;
                    // 回填上次已选奖励
                    if (row.rewards && Array.isArray(row.rewards)) {
                        this.auditForm.rewards = row.rewards.map(x => JSON.stringify(x));
                    }
                } else {
                    this.$message.error(res.msg);
                }
            } catch (e) {
                this.rewardOptions = [];
                this.$message.error('获取奖励项失败');
            } finally {
                // 只要奖励请求回来，不管成功失败都显示弹窗，并关闭按钮loading
                this.auditDialogLoading = false;
                this.auditDialog.visible = true;
                this.$set(this.auditBtnLoading, row.id, false);
            }
        },
        // 重置审核表单
        resetAuditForm() {
            this.auditForm = {
                status: 2,
                reason: '',
                rewards: []
            }
            this.$nextTick(() => {
                this.$refs.auditFormRef && this.$refs.auditFormRef.clearValidate()
            })
        },
        // 审核提交
        async submitAudit() {
            // 先校验表单
            this.$refs.auditFormRef.validate(async valid => {
                if (!valid) return; // 校验不通过
                const row = this.auditDialog.currentRow
                this.auditLoading = true
                this.$set(this.auditBtnLoading, row.id, true)
                try {
                    let postData = {
                        id: row.id,
                        status: this.auditForm.status,
                        reason: this.auditForm.reason,
                    }
                    if (this.auditForm.status === 2) {
                        postData.rewards = this.auditForm.rewards.map(s => JSON.parse(s));
                    }
                    let { data: res } = await axios.post(API_BASE + '/reward/apply/audit', postData)
                    if (res.code === 0) {
                        this.$message.success('审核成功')
                        this.auditDialog.visible = false
                        this.getList()
                    } else {
                        this.$message.error(res.msg || '审核失败')
                    }
                } catch (e) {
                    this.$message.error(e.message || '操作失败')
                }
                this.auditLoading = false
                this.$delete(this.auditBtnLoading, row.id)
            });
        },
        // 详情弹窗
        viewDetail(row) {
            this.detailData = { ...row }
            if (this.detailData.rewards && typeof this.detailData.rewards === 'string') {
                try {
                    this.detailData.rewards = JSON.parse(this.detailData.rewards)
                } catch { this.detailData.rewards = [] }
            }
            this.detailDialogVisible = true
        },
        // 状态文字
        getStatusText(status) {
            return { 1: '审核中', 2: '通过', 3: '拒绝' }[status] || '未知'
        },
        // 状态类型
        getStatusType(status) {
            return { 1: 'warning', 2: 'success', 3: 'danger' }[status] || 'info'
        },
        // 时间格式化
        formatTime(val) {
            return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
        }
    }
}
</script>

<style scoped>
.reward-management {
    padding: 30px 10px;
}

.audit-info {
    margin-bottom: 20px;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.el-radio {
    margin-right: 20px;
    margin-bottom: 10px;
}

.el-radio.is-bordered {
    padding: 10px 15px;
    border-radius: 6px;
}

.dialog-footer {
    text-align: right;
}

::v-deep .el-radio-group {
    vertical-align: baseline;
}
</style>